﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace MyMusicCollection.Model
{
	class ArtistHandler
	{
		public Artist GetArtist(string aUri)
		{
			Artist theArtist = new Artist();

			DiscogsReader dcReader = new DiscogsReader();
			XmlTextReader xmlReader = dcReader.GetArtistResponse(aUri);
			XmlDocument xmlDoc = new XmlDocument();

			if (xmlReader == null)
			{
				Console.WriteLine("Fel vid kopplingen till Discogs.");
				return null;
			}

			try
			{
				
				xmlReader.Read();
				xmlDoc.LoadXml(xmlReader.ReadOuterXml());
				xmlReader.Close();

				//Hämtar namnet
				theArtist.mName = xmlDoc.SelectSingleNode("resp/artist/name").InnerText;

				//Hämtar albumen
				XmlNodeList nList = xmlDoc.SelectNodes("resp/artist/releases/release");

				foreach (XmlNode node in nList)
				{
					ArtistAlbum album = new ArtistAlbum();
					XmlAttributeCollection nodeAtt = node.Attributes;

					if (nodeAtt.GetNamedItem("type").InnerText == "Main")
					{
						album.mID = int.Parse(nodeAtt.GetNamedItem("id").InnerText);
						album.mArtist = theArtist.mName;

						//Titel
						if (node.SelectSingleNode("title") != null)
						{
							album.mTitle = node.SelectSingleNode("title").InnerText;
						}
						else
						{
							album.mTitle = "titel_ej_tillgänglig";
						}

						//Format
						if (node.SelectSingleNode("format") != null)
						{
							album.mFormat = node.SelectSingleNode("format").InnerText;
						}
						else
						{
							album.mFormat = "Okänt format";
						}

						//Label
						if (node.SelectSingleNode("label") != null)
						{
							album.mLabel = node.SelectSingleNode("label").InnerText;
						}
						else
						{
							album.mLabel = "Okänt skivbolag";
						}

						//År
						if (node.SelectSingleNode("year") != null)
						{
							album.mYear = node.SelectSingleNode("year").InnerText;
						}
						else
						{
							album.mYear = "XXXX";
						}

						theArtist.mAlbumList.Add(album);
					}
				}

				return theArtist;
			}
			catch (Exception e)
			{
				Console.WriteLine("Något gick fel med kopplingen till Discogs.");
				xmlReader.Close();
				return null;
			}
		}
	}
}
